<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
      <el-breadcrumb-item>
        <router-link class="router-link" :to="{path: '/training/student'}">学员列表</router-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item>基本身体数据</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="content">
      <e-heading grade='1'>基本身体数据</e-heading>
      <div style="margin-bottom:15px;">
        学员：{{studentDetailInfo.name}}(<img width="20" height="20" src="/static/images/u206.png">{{new Date(studentDetailInfo.birthday).format()}})
      </div>
      <el-row>
        <el-col :span="18">
          <el-radio-group v-model="categoryId">
            <el-radio-button
              v-for="item in categoryList"  
              :key="item.id"
              :label="item.categoryId">
              {{item.categoryName}}
              </el-radio-button>
          </el-radio-group>
        </el-col> 
        <el-col :span="4" :offset="hasCateData ? 2 : 20">
          <el-button type="link" class="log-btn" @click="addLog">添加记录</el-button>
          <router-link :to="{
            path: '/training/student/history',
            query: this.$route.query
          }">
            <el-button type="link" class="log-btn">历史记录</el-button>
          </router-link>
        </el-col>
      </el-row>


      <div class="echarts" v-if="hasCateData" v-loading="loading">
        <LineChart  class="e-line-chart"
          v-if="ready"
          :key="categoryId"
          :option="option"
          :onReady="onReady"
            />
      </div>
      <div class="center placehold" v-else>
        <h2 style="font-size:24px;">暂无内容</h2>
        <p>未设置学员身体数据显示项，无法显示详细数据</p>
        <router-link :to="{
          path:'/training/student/body-data'
        }">
          <el-button type="primary">去设置</el-button>
        </router-link>
      </div>

    </div>

    <data-dialog
      v-if="dialogVisible"
      :visible="dialogVisible"
      :isEdit="false"
      :data="[]"
      :recordDate="recordDate"
      :category="category"
      @submit="handleSubmit"
      @close="dialogVisible = false">
    </data-dialog>
  </div>
  
</template>
<script>
import validator from 'utils/validator'
import {sortByTime} from 'utils'
import DataDialog from './components/chart/DataDialog'
import IEcharts from 'vue-echarts-v3/src/full.js'
import LineChart from './components/chart/LineChart'
import api from 'api/train'
export default {
  components: {
    DataDialog, IEcharts, LineChart
  },
  computed: {
    trainBodyData () {
      return this.$store.getters.train_body_data
    },
    category () {
      return this.$store.getters.train_body_data_category
    }
  },
  watch: {
    categoryId (val, OldVal) {
      this.ready = false
      this.cate = this.categoryList.find(item => {
        return item.categoryId === val
      })
      let dataList = []
      this.trainBodyData.forEach((row) => {
        let bodyData = row.studentBodyDataList
        bodyData.forEach((item) => {
          if (item.categoryId === this.cate.categoryId) {
            dataList.push([row.recordAge, item.dataValue, item.recordDate])
          }
        })
      })
      this.data = this.option.series[0].data = dataList
      this.option.yAxis.name = `单位:${this.cate.unitName}`
      this.option.yAxis.min = this.cate.echartMinValue
      this.option.yAxis.max = this.cate.echartMaxValue
      this.option.yAxis.splitNumber = this.cate.echartSection
      this.option.tooltip.formatter = (params) => {
        return `日期: ${new Date(params.data[2]).format()}<br>${this.cate.categoryName}: ${params.data[1].toFixed(2)}${this.cate.unitName}`
      }
      this.ready = true
    }
  },
  mounted () {
    this.loading = true
    this.getData()
    api.studentDetail({
      studentId: this.$route.query.id,
      operationFlag: true}).then(res => {
      this.studentDetailInfo = res.data
    })
  },
  data () {
    const symbolSize = 15
    return {
      loading: false,
      validator,
      dialogVisible: false,
      recordDate: +new Date(),
      rules: {},
      cate: {},
      categoryId: '',
      categoryName: '',
      xLabels: [],
      symbolSize,
      categoryList: [],
      form: {},
      ready: false,
      bodyData: [],
      data: [],
      unit: '',
      minAge: 3,
      maxAge: 21,
      minValue: 0,
      maxValue: 250,
      option: {
        title: {
          text: ''
        },
        tooltip: {
          triggerOn: 'none',
          formatter: (params) => {
            return `日期: ${new Date(params.data[2]).format()}<br>${this.cate.categoryName}: ${params.data[1].toFixed(2)}${this.cate.unitName}`
          }
        },
        grid: {
        },
        xAxis: {
          min: 3,
          max: 20,
          data: this.xLabels,
          name: '岁',
          type: 'value',
          axisLine: {onZero: false}
        },
        yAxis: {
          splitNumber: 5,
          min: 0,
          max: 250,
          name: ``,
          type: 'value',
          axisLine: {onZero: false}
        },
        series: [
          {
            id: 'a',
            type: 'line',
            smooth: true,
            symbolSize: this.symbolSize,
            data: this.data
          }
        ]
      },
      ins: null,
      echarts: null,
      hasCateData: false,
      studentDetailInfo: {}
    }
  },
  methods: {
    getData () {
      this.ready = false
      api.getBodyDate({
        studentId: this.$route.query.id
      }).then((res) => {
        let {categoryList, studentBodyDataList} = res.data
        this.hasCateData = categoryList.length > 0
        this.categoryList = this.hasCateData ? categoryList : []
        this.cate = categoryList[0]
        this.categoryId = this.cate.categoryId
        this.unit = this.cate.unitName
        this.categoryName = this.cate.categoryName
        this.minValue = this.cate.echartMinValue
        this.maxValue = this.cate.echartMaxValue
        this.$store.commit('TRAIN_BODY_DATA_CATEGORY', this.categoryList)
        if (studentBodyDataList.length) {
          let dataList = sortByTime(studentBodyDataList, 'recordAge')
          this.$store.commit('TRAIN_BODY_DATA', dataList)
          let data = []
          dataList.forEach((row) => {
            let bodyDataList = row.studentBodyDataList
            bodyDataList.forEach((item) => {
              if (item.categoryId === this.categoryId) {
                data.push([row.recordAge, item.dataValue, item.recordDate])
              }
            })
          })
          this.data = data
          this.option.series[0].data = this.data
          this.option.yAxis.name = `单位:${this.unit}`
          this.option.yAxis.min = this.minValue
          this.option.yAxis.max = this.maxValue
          this.ready = true
          this.loading = false
        } else {
          this.loading = false
          this.ready = true
        }
      }).catch(() => {
        this.loading = false
      })
    },
    onReady (ins, echarts) {
      const that = this
      this.ins = ins
      this.echarts = echarts
      const updatePosition = () => {
        ins.setOption({
          graphic: echarts.util.map(this.data, (item, dataIndex) => {
            return {
              position: ins.convertToPixel('grid', item)
            }
          })
        })
      }
      const showTooltip = (dataIndex) => {
        ins.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: dataIndex
        })
      }
      const hideTooltip = (dataIndex) => {
        ins.dispatchAction({
          type: 'hideTip'
        })
      }

      const setOption = () => {
        ins.setOption({
          graphic: echarts.util.map(that.data, (item, dataIndex) => {
            return {
              type: 'circle',
              position: ins.convertToPixel('grid', item),
              shape: {
                cx: 0,
                cy: 0,
                r: that.symbolSize / 2
              },
              invisible: true,
              draggable: false,
              onmousemove: echarts.util.curry(showTooltip, dataIndex),
              onmouseout: echarts.util.curry(hideTooltip, dataIndex),
              z: 100
            }
          })
        })
      }

      setTimeout(() => {
        if (!that.data.length) {
          setTimeout(() => {
            setOption()
          }, 200)
          return false
        }
        setOption()
      }, 500)
      window.addEventListener('resize', updatePosition)
      ins.on('dataZoom', updatePosition)
    },
    handleSubmit (form) {
      api.saveBodyData({
        studentId: this.$route.query.id,
        recordDate: +new Date(form.recordDate),
        bodyDataDetailJson: form.bodyDataDetailJson
      }, {successMsg: '保存成功'}).then((res) => {
        this.getData()
        this.dialogVisible = false
      }).catch((err) => {
        console.log(err)
      })
    },
    addLog () {
      this.dialogVisible = true
    }
  }
}
</script>
<style scoped lang="scss">
.echarts{
  width: 800px;
  height: 800px;
  margin: 0 auto;
}
.e-line-chart{
  width: 800px!important;
  height: 800px!important;
  margin: 0 auto;
}
.log-btn{
  line-height: 40px;
}
.placehold{
  color: #909090;
  padding: 40px 0;
  p{
    margin: 1px 0 15px; 
  }
}
</style>
